package com.example.xd.defaultcall;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.telecom.Call;
import android.telecom.VideoProfile;
import android.util.Log;


/**
 * @auther XuDan on 2020/6/2.
 */
public class PhoneCallManager {
    public static Call call;
    private AudioManager mAudioManager;


    @SuppressLint("HandlerLeak")
    public PhoneCallManager(Context context) {
        mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setMode(AudioManager.MODE_IN_CALL);
    }

    /**
     * 接听电话
     */
    public void answer() {
        if (call != null) {
            call.answer(VideoProfile.STATE_AUDIO_ONLY);
            openSpeaker();
        }
    }

    private void openSpeaker() {
        if (mAudioManager != null) {
            if (mAudioManager.isSpeakerphoneOn()) {
                Log.i("xd---------", "关掉免提");
                mAudioManager.setSpeakerphoneOn(true);
                mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                        AudioManager.STREAM_VOICE_CALL);
            } else {
                Log.i("xd---------", "打开免提");
                mAudioManager.setSpeakerphoneOn(false);
                mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL),
                        AudioManager.STREAM_VOICE_CALL);
            }
        }
    }

    public void setSpeakMode() {
        if (mAudioManager != null) {
            if (mAudioManager.isSpeakerphoneOn()) {
                Log.i("xd---------", "关掉免提");
                mAudioManager.setSpeakerphoneOn(false);
                mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL),
                        AudioManager.STREAM_VOICE_CALL);
            } else {
                Log.i("xd---------", "打开免提");
                mAudioManager.setSpeakerphoneOn(true);
                mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                        mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                        AudioManager.STREAM_VOICE_CALL);
            }


        }
    }

    /**
     * 断开通话
     */
    public void disconnect() {
        if (call != null) {
            call.disconnect();
        }
    }

    /**
     * 销毁资源
     */
    public void destroy() {
        call = null;
        mAudioManager = null;
    }
}
